#!/bin/bash

# 头条自动发文系统 - Gitee部署脚本
# 适用于阿里云服务器 (DNF Linux系统)

set -e

echo "🚀 开始从Gitee部署头条自动发文系统..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置变量
GITEE_REPO_URL=""
PROJECT_DIR="/opt/toutiao-auto-publish"
BRANCH="main"

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}❌ 请提供Gitee仓库地址${NC}"
    echo "用法: $0 <gitee-repo-url> [branch]"
    echo "示例: $0 https://gitee.com/your-username/toutiao-auto-publish.git main"
    exit 1
fi

GITEE_REPO_URL=$1
if [ $# -ge 2 ]; then
    BRANCH=$2
fi

echo -e "${BLUE}📋 部署配置:${NC}"
echo "仓库地址: $GITEE_REPO_URL"
echo "分支: $BRANCH"
echo "部署目录: $PROJECT_DIR"
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}请使用root用户运行此脚本${NC}"
    exit 1
fi

# 1. 更新系统
echo -e "${BLUE}📦 更新系统包...${NC}"
dnf update -y

# 2. 安装Git
echo -e "${BLUE}📥 安装Git...${NC}"
if ! command -v git &> /dev/null; then
    dnf install -y git
    echo -e "${GREEN}✅ Git安装完成${NC}"
else
    echo -e "${YELLOW}⚠️ Git已安装${NC}"
fi

# 3. 安装Docker
echo -e "${BLUE}🐳 安装Docker...${NC}"
if ! command -v docker &> /dev/null; then
    dnf install -y dnf-plugins-core
    dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
    dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    
    systemctl start docker
    systemctl enable docker
    echo -e "${GREEN}✅ Docker安装完成${NC}"
else
    echo -e "${YELLOW}⚠️ Docker已安装${NC}"
fi

# 4. 安装Docker Compose
echo -e "${BLUE}🔧 安装Docker Compose...${NC}"
if ! command -v docker-compose &> /dev/null; then
    # 使用国内镜像加速下载
    curl -L "https://get.daocloud.io/docker/compose/releases/download/v2.23.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    echo -e "${GREEN}✅ Docker Compose安装完成${NC}"
else
    echo -e "${YELLOW}⚠️ Docker Compose已安装${NC}"
fi

# 5. 克隆项目代码
echo -e "${BLUE}📥 克隆项目代码...${NC}"
if [ -d "$PROJECT_DIR" ]; then
    echo -e "${YELLOW}⚠️ 项目目录已存在，正在更新...${NC}"
    cd $PROJECT_DIR
    git pull origin $BRANCH
else
    echo -e "${BLUE}📥 克隆仓库...${NC}"
    git clone -b $BRANCH $GITEE_REPO_URL $PROJECT_DIR
    cd $PROJECT_DIR
fi

# 6. 创建必要目录
echo -e "${BLUE}📁 创建数据目录...${NC}"
mkdir -p data logs uploads browser_data

# 7. 设置目录权限
echo -e "${BLUE}🔐 设置目录权限...${NC}"
chmod 755 data logs uploads browser_data
chown -R 1000:1000 data logs uploads browser_data

# 8. 创建环境配置文件
echo -e "${BLUE}⚙️ 创建环境配置文件...${NC}"
if [ ! -f ".env" ]; then
    cat > .env << EOF
# 应用配置
SECRET_KEY=$(openssl rand -hex 32)
DEBUG=False

# 服务器配置
HOST=0.0.0.0
PORT=8000

# 浏览器配置
BROWSER_HEADLESS=true
BROWSER_NO_SANDBOX=true
BROWSER_DISABLE_GPU=true
BROWSER_DISABLE_DEV_SHM=true

# 日志配置
LOG_LEVEL=INFO
LOG_FILE=/app/logs/app.log

# 文件上传配置
UPLOAD_DIR=/app/uploads
MAX_FILE_SIZE=10485760

# 头条配置
TOUTIAO_LOGIN_URL=https://mp.toutiao.com/auth/page/login/
TOUTIAO_PUBLISH_URL=https://mp.toutiao.com/profile_v4/graphic/publish
TOUTIAO_TITLE_URL=https://mp.toutiao.com/profile_v4/graphic/articles

# AI配置（可选）
# DEEPSEEK_API_KEY=your-deepseek-api-key-here
EOF
    echo -e "${GREEN}✅ 环境配置文件创建完成${NC}"
else
    echo -e "${YELLOW}⚠️ 环境配置文件已存在，跳过创建${NC}"
fi

# 9. 配置Docker镜像加速
echo -e "${BLUE}🚀 配置Docker镜像加速...${NC}"
mkdir -p /etc/docker
cat > /etc/docker/daemon.json << EOF
{
    "registry-mirrors": [
        "https://docker.mirrors.ustc.edu.cn",
        "https://hub-mirror.c.163.com",
        "https://mirror.baidubce.com"
    ],
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m",
        "max-file": "3"
    }
}
EOF
systemctl restart docker

# 10. 配置防火墙
echo -e "${BLUE}🔥 配置防火墙...${NC}"
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=8000/tcp
    firewall-cmd --reload
    echo -e "${GREEN}✅ 防火墙配置完成 (端口8000已开放)${NC}"
else
    echo -e "${YELLOW}⚠️ 未检测到firewall-cmd，请手动开放8000端口${NC}"
fi

# 11. 构建Docker镜像
echo -e "${BLUE}🔨 构建Docker镜像...${NC}"
docker-compose build --no-cache

# 12. 启动服务
echo -e "${BLUE}🚀 启动服务...${NC}"
docker-compose up -d

# 13. 创建systemd服务
echo -e "${BLUE}🔧 创建systemd服务...${NC}"
cat > /etc/systemd/system/toutiao-auto-publish.service << EOF
[Unit]
Description=Toutiao Auto Publish Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${PROJECT_DIR}
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
ExecReload=/usr/local/bin/docker-compose restart
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable toutiao-auto-publish

# 14. 创建更新脚本
echo -e "${BLUE}📝 创建更新脚本...${NC}"
cat > update.sh << 'EOF'
#!/bin/bash
echo "🔄 更新头条自动发文系统..."

cd /opt/toutiao-auto-publish

# 拉取最新代码
git pull origin main

# 重新构建镜像
docker-compose build --no-cache

# 重启服务
docker-compose down
docker-compose up -d

echo "✅ 更新完成！"
EOF
chmod +x update.sh

# 15. 等待服务启动
echo -e "${BLUE}⏳ 等待服务启动...${NC}"
sleep 10

# 16. 检查服务状态
echo -e "${BLUE}🔍 检查服务状态...${NC}"
if docker-compose ps | grep -q "Up"; then
    echo -e "${GREEN}✅ 服务启动成功${NC}"
else
    echo -e "${RED}❌ 服务启动失败，请查看日志${NC}"
    docker-compose logs
fi

# 17. 获取服务器IP
SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || curl -s ipinfo.io/ip 2>/dev/null || echo "your-server-ip")

# 18. 显示部署结果
echo -e "${GREEN}"
echo "🎉 部署完成！"
echo "=================================="
echo "项目目录: ${PROJECT_DIR}"
echo "访问地址: http://${SERVER_IP}:8000"
echo "本地访问: http://localhost:8000"
echo "日志目录: ${PROJECT_DIR}/logs"
echo "数据目录: ${PROJECT_DIR}/data"
echo "=================================="
echo -e "${NC}"

echo -e "${YELLOW}📋 管理命令:${NC}"
echo "查看状态: docker-compose ps"
echo "查看日志: docker-compose logs -f"
echo "重启服务: docker-compose restart"
echo "停止服务: docker-compose down"
echo "更新系统: ./update.sh"
echo ""
echo -e "${BLUE}💡 Chrome支持说明:${NC}"
echo "✅ 已安装 Google Chrome 浏览器"
echo "✅ 已配置 Xvfb 虚拟显示"
echo "✅ 已安装中文字体支持"
echo "✅ 已优化 DrissionPage 环境"
echo ""
echo -e "${BLUE}🔧 systemd服务:${NC}"
echo "启动: systemctl start toutiao-auto-publish"
echo "停止: systemctl stop toutiao-auto-publish"
echo "状态: systemctl status toutiao-auto-publish"
echo ""
echo -e "${GREEN}✅ Gitee部署脚本执行完成！${NC}"
